<!-- 登录 -->
<template>
  <div class="muse-login-wrapper">
    <!-- logo等 -->
    <div class="company-logo-wrapper">
      <img class="logo-full" src="@/assets/images/login-page-logo-s.png" />
      <!-- <img class="company-logo" src="@/assets/images/logo-big.png" />
      <p class="company-name">精策云</p> -->
    </div>

    <div class="muse-login-function-container">
      <div class="strechable-right">
        <!-- 居中的登录块块 -->
        <div class="centered-wrapper">
          <Spin size="large" fix v-if="isLoading"></Spin>
          <!-- 欢迎标题 -->
          <p class="welcome-title">欢迎使用<span class="blue">精策云</span></p>

          <!-- 登录方式切换 -->
          <div class="login-tab">
            <div class="login-tab-rail">
              <div class="tab-content" :class="{ 'current' : currentTab === 1 }" @click="handleTabChange(1)">
                <div class="tab-name">
                  账户登录
                </div>
              </div>
              <div class="tab-content" :class="{ 'current' : currentTab === 2 }" @click="handleTabChange(2)">
                <div class="tab-name">
                  手机号登录
                </div>
              </div>
            </div>
          </div>
          
          <div class="login-form-wrapper">
            <!-- 账户密码 -->
            <template v-if="currentTab == 1">
              <!-- 用户名 -->
              <div class="input-row" :class="focusTarget === 'username' ? `active` : ``" @click.stop="handleInputFocus('username')">
                <div class="prefix">
                  <IconFont icon="user-single-solid" size="22" />
                </div>
                <div class="input">
                  <input v-model.trim="username" placeholder="请输入注册的用户名" />
                </div>
              </div>
              <!-- 密码 -->
              <div class="input-row" :class="focusTarget === 'password' ? `active` : ``" @click.stop="handleInputFocus('password')">
                <div class="prefix">
                  <IconFont icon="lock" size="22" />
                </div>
                <div class="input">
                  <input autoComplete="new-password" v-model.trim="password" placeholder="请输入密码" :type="showPlaintext === true ? 'text' : 'password'"/>
                </div>
                <div class="suffix show-plain-text" :class="{ 'active': showPlaintext === true }" @click="showPlaintext = !showPlaintext">
                  <IconFont :icon="showPlaintext === true ? 'eye-close' : 'eye-open'" size="18" />
                </div>
              </div>
            </template>
            <!-- 手机号 -->
            <template v-if="currentTab == 2">
              <!-- 手机号 -->
              <div class="input-row" :class="focusTarget === 'mobile' ? `active` : ``" @click.stop="handleInputFocus('mobile')">
                <div class="prefix">
                  <IconFont icon="mobile" size="22" />
                </div>
                <div class="input">
                  <input v-model.trim="mobile" placeholder="请输入手机号" />
                </div>
              </div>
              <!-- 验证码 -->
              <div class="input-row" :class="focusTarget === 'verifyCode' ? `active` : ``" @click.stop="handleInputFocus('verifyCode')">
                <div class="prefix">
                  <IconFont icon="captcha" size="22" />
                </div>
                <div class="input captcha-wrapper">
                  <input autoComplete="new-password" v-model.trim="verifyCode" placeholder="请输入验证码"/>
                  <div class="slide-verify-wrapper" v-if="showCountDown == true">
                    <p class="get-captcha count-down">（{{ countDown }}）秒后重新获取</p>
                  </div>
                  <slideVerify class="slide-verify-wrapper" ref="slideVerifyRef" @captchaFn="onCaptchaSuccess" v-if="showCountDown == false">
                    <p class="get-captcha" @click.stop="handleGetCaptcha">获取验证码</p>
                  </slideVerify>
                </div>
              </div>
            </template>
          </div>

          <!-- 自动登录 -->
          <div class="auto-login">
            <div class="check-box-wrapper">
              <Checkbox v-model="autoLogin" size="large">自动登录</Checkbox>
            </div>
            <a class="blue-color forget-password" @click="retrievePassword()">忘记密码</a>
          </div>

          <!-- 登录按钮 -->
          <div class="login-button-field">
            <a class="login-button" @click="handleSubmit">
              登录
            </a>
          </div>

          <div class="register-field">
            <span>没有账号？</span>
            <a @click="regiserNewAccount()">点击此处前往注册</a>
          </div>
        </div>

      </div>
    </div>

  </div>
</template>

<script>
import { mapActions } from "vuex";
import mixins from "../mixins";
import slideVerify from "@/components/slideVerify";
import { frameInRoutes } from "@/router/routes";
import BasicLayout from "@/layouts/basic-layout";
import { encryptByDES, decryptByDES } from "@/utils/encrypFile.js";

import {
  getSlideVerifyImage,
  ValidSlideVerifyImage, // 上传滑块位置
  SendVerifyMobileSms, // 获取验证码
} from "@/api/common.js";

export default {
  name: 'Pages.Account.Login.Index',
  components: { slideVerify },
  data() {
    return {
      isLoading: false, 

      currentTab: 1,
      focusTarget: null,
      autoLogin: true, //自动登录

      username: '', //用户名
      password: '', //密码

      mobile: '', //手机号
      verifyCode: '', //验证码

      showPlaintext: false, //显示密码

      showCountDown: false, //显示倒计时
      countDown: 0, //倒计时
      countDownInstance: null, //计时器
    }
  },
  mounted() {
    setTimeout(() => {
      window.addEventListener("keydown", this.keyDown);
    }, 24)
  },
  beforeDestroy() {
    window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    ...mapActions("admin/account", ["login"]),
    /**
     * @description 执行登录
     */
    async handleSubmit() {
      let valid = await this.beforeLogin();
      if (valid) {
        this.isLoading = true;
        let params = {
          username: this.currentTab == 1 ? this.username : this.mobile,
          password: this.currentTab == 1 ? this.password : this.verifyCode,
          type: this.currentTab,
        }
        this.login(params).then(() => {
          this.isLoading = false;
          this.afterLogin();
        }).catch(() => {
          this.isLoading = false;
        });
      }
    },

    /**
     * @description 获取验证码
     */
    handleGetCaptcha() {
      if (!this.mobile) {
        this.$Message.error('请输入手机号');
        return;
      }
      this.$refs.slideVerifyRef.innuser();
    },

    /**
     * @description 图片验证码验证成功
     */
    async onCaptchaSuccess() {
      let data = await getSlideVerifyImage();
      let verifyParams = {
        mobile: this.mobile,
      };
      let verifyCode = await SendVerifyMobileSms(verifyParams);
      this.$Message.success('验证码已发送');
      this.showCountDown = true;
      this.countDown = 60;
      this.createCountDown();
    },

    /**
     * @description 生产倒计时
     */
    createCountDown() {
      this.countDownInstance = setInterval(() => {
        this.countDown--;
        if (this.countDown == 0) {
          this.clearCountDown(); //清理倒计时
        }
      }, 1000)
    },

    /**
     * @description 销毁倒计时
     */
    clearCountDown() {
      clearInterval(this.countDownInstance);
      this.showCountDown = false;
    },

    /**
     * @description 切换登录类型
     * @param tabName 
     */
    handleTabChange(tabName) {
      this.currentTab = tabName;
      this.$nextTick(() => {
        this.username = '';
        this.password = '';
        this.mobile = '';
        this.verifyCode = '';
      })
    },

    /**
     * @description 输入窗聚焦事件
     * @param {*} targetName 
     */
    handleInputFocus(targetName) {
      this.focusTarget = targetName;
    },

    /**
     * @description 登录前步骤
     */
    beforeLogin() {
      const _that = this;
      return new Promise(resolve => {
        let valid = checkForm();
        resolve(valid);
      })

      /**
       * @description 表单检查函数
       */
      function checkForm() {
        if (_that.currentTab == 1) {
          if (!_that.username) {
            _that.$Message.warning('请输入账号');
            return false;
          }
          if (!_that.password) {
            _that.$Message.warning('请输入密码');
            return false;
          }
        } else if (_that.currentTab == 1) {
          if (!_that.mobile) {
            _that.$Message.warning('请输入手机号');
            return false;
          }
          if (_that.$Regulars.mobile(_that.mobile) === false) {
            _that.$Message.warning('请输入正确的手机号');
            return false;
          }
          if (!_that.verifyCode) {
            _that.$Message.warning('请输入验证码');
            return false;
          }
        }
        return true;
      }
    },

    /**
     * @description 登录后续
     */
    afterLogin() {
      let meta = {
        auth: true,
      };
      let routes = [
        {
          path: "/",
          name: "home",
          redirect: {
            name: `homepage`,
          },
          meta,
          component: BasicLayout,
          children: [
            {
              path: "/home",
              name: `homepage`,
              meta: {
                ...meta,
                title: "首页",
                closable: false,
              },
              component: () => import("@/pages/home"),
            },
          ],
        },
      ];
      this.$router.addRoutes(routes);
      // 完整的 frameInRoutes，更新 vuex 的数据
      const newRoutes = frameInRoutes.concat(routes);
      this.$store.commit("admin/page/init", newRoutes);
      let useStatusStr = localStorage.getItem("useStatus");
      if (useStatusStr) {
        localStorage.clear("useStatus");
      }
      // return;
      // 重定向对象不存在则返回顶层路径
      this.$router.replace(this.$route.query.redirect || "/home");
      this.isLoading = false;
    },
    
    /**
     * 忘记密码
     */
    retrievePassword() {
      this.$router.push({
        path: "/retrievePassword",
      });
    },

    /**
     * @description 注册
     */
    regiserNewAccount() {
      this.$router.push({
        name: "register",
      });
    },

    /**
     * @description 回车登录
     * @param e 
     */
    keyDown(e) {
      if (e.keyCode == 13) {
        this.handleSubmit();
      }
    }
  }
};
</script>

<style lang="less" scoped>
@import '../../../assets/muse_theme/less/pages/login-index.less';
</style>
